import resolve from "@rollup/plugin-node-resolve"; // 告诉 Rollup 如何查找外部模块
import commonjs from "@rollup/plugin-commonjs"; // 将CommonJS模块转换为 ES2015 供 Rollup 处理
import esbuild from "rollup-plugin-esbuild";
import vue from "rollup-plugin-vue"; // 处理vue文件
import fs from "fs-extra"; // 写文件
import path from "path";
import image from '@rollup/plugin-image';
import postcss from 'rollup-plugin-postcss';
import less from 'less';

const INPUT_PATH = path.resolve(__dirname, "./packages");
const OUTPUT_PATH = path.resolve(__dirname, "./dist/es/dist");

const processLess = function(context, payload) {
  return new Promise(( resolve, reject ) => {
    less.render({
      file: context
    }, function(err, result) {
      if( !err ) {
        resolve(result);
      } else {
        reject(err);
      }
    });

    less.render(context, {})
    .then(function(output) {
      if( output && output.css ) {
        resolve(output.css);
      } else {
        reject({})
      }
    },
    function(err) {
      reject(err)
    });

  })
}

let dirs = fs.readdirSync(`${INPUT_PATH}/components`).map((name) => {
  return {
    input: `${INPUT_PATH}/components/${name}/index.ts`,
    external: ["vue"],
    plugins: [
      resolve({ extensions: [".ts"] }),
      vue(),
      postcss({
        extract: true,
        minimize: true,
        process: processLess,
      }),
      image(),
      esbuild(),
      commonjs()],
    output: {
      name: "index",
      file: `${OUTPUT_PATH}/${name}/index.js`,
      format: "es",
    },
  };
});

export default dirs;
